package com.shenmazong.scheduling;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.dto.TbCompany;
import com.shenmazong.mapper.TbCompanyJobMapper;
import com.shenmazong.mapper.TbCompanyMapper;
import com.shenmazong.vo.CompanyJobVo;
import com.shenmazong.vo.CompanyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 阿瑞
 * @version 1.0
 * @description TODO
 * @class CompanyCache ???
 * @date 2021/9/23 18:57
 */
@Component
public class CompanyCache {
    @Autowired
    private TbCompanyMapper tbCompanyMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private TbCompanyJobMapper tbCompanyJobMapper;
    @Scheduled(fixedRate = 1000)
    public void  mysqlToEsCompany(){
        //创建索引
        if (!elasticsearchRestTemplate.indexOps(CompanyVo.class).exists()){
            elasticsearchRestTemplate.indexOps(CompanyVo.class).create();
            Document mapping = elasticsearchRestTemplate.indexOps(CompanyVo.class).createMapping();
            elasticsearchRestTemplate.indexOps(CompanyVo.class).putMapping(mapping);
        }
        //获取数据
        List<CompanyVo> list = tbCompanyMapper.getAllCompany();
        //判断长度
        if (list.size()>0){
            //修改状态码
            for (CompanyVo companyVo : list) {
                List<CompanyJobVo> test=tbCompanyJobMapper.findAllJob(companyVo.getCompanyId());
                companyVo.setList(test);
                TbCompany select = tbCompanyMapper.selectById(companyVo.getCompanyId());
                select.setSyncEs((byte) 1);
                tbCompanyMapper.updateById(select);
            }
            elasticsearchRestTemplate.save(list);
            System.err.println("公司同步完成");
        }else {
            System.err.println("没有需要同步的公司");
        }
    }

}
